package com.ruoyi.web.controller.xiaomi;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.bye.xiaomi_mall.domain.TdOrderDetail;
import com.bye.xiaomi_mall.domain.TdUser;
import com.bye.xiaomi_mall.service.ITdGoodsService;
import com.bye.xiaomi_mall.service.ITdShoppingCartService;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.bye.xiaomi_mall.domain.TdOrder;
import com.bye.xiaomi_mall.service.ITdOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.Util.TokenUtil.decrypt;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2025-03-15
 */

@RestController
@RequestMapping("/xiaomi_mall/order")
public class TdOrderController extends BaseController {
    @Autowired
    private ITdOrderService tdOrderService;
    @Autowired
    private ITdGoodsService goodsService;
    @Autowired
    private ITdShoppingCartService shoppingCartService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('xiaomi_mall:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(TdOrder tdOrder) {
        startPage();
        List<TdOrder> list = tdOrderService.selectTdOrderList(tdOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('xiaomi_mall:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TdOrder tdOrder) {
        List<TdOrder> list = tdOrderService.selectTdOrderList(tdOrder);
        ExcelUtil<TdOrder> util = new ExcelUtil<TdOrder>(TdOrder.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('xiaomi_mall:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tdOrderService.selectTdOrderById(id));
    }

    /**
     * 新增订单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody TdOrder tdOrder) throws Exception {

        tdOrder.setOrderStatus("0");
        tdOrder.setCreateTime(DateUtils.getNowDate());
        tdOrder.setOrderCode(String.valueOf(System.currentTimeMillis()));
        tdOrder.setUserId(Long.valueOf(decrypt(tdOrder.getMiUserToken())));
//        添加订单和订单详情
        int i = tdOrderService.insertTdOrder(tdOrder);
        //          向mq发送消息  增加销量  生成支付记录交易流水放到mq中操作
        rabbitTemplate.convertAndSend("payback.fanout", "", tdOrder.getOrderCode());
//        使用mq创建延迟消息  当用户规定时间没有支付  执行监听延时队列的消费者的逻辑

        rabbitTemplate.convertAndSend("payback.order_delay_exchange", "delay", tdOrder.getOrderCode(), message -> {
            // 设置延迟消息  毫秒
            message.getMessageProperties().setDelay(30 * 1000);
            return message;
        });

        return AjaxResult.success().put("orderCode", tdOrder.getOrderCode());
    }


    @PostMapping("/selectOrderInfoByOrderCode")
    public AjaxResult selectOrderInfoByOrderCode(@RequestBody TdOrder tdOrder) throws Exception {
        TdOrder orderInfo = tdOrderService.selectOrderInfoByOrderCode(tdOrder.getOrderCode());
        if (null != orderInfo) {
            return AjaxResult.success().put("orderInfo", orderInfo);
        }
        return AjaxResult.error("当前订单不存在");
    }

    @PostMapping("/selectOrderInfoByToken")
    public AjaxResult selectOrderInfoByToken(@RequestHeader("miUserToken") String miUserToken) throws Exception {
        String userID = decrypt(miUserToken);
        List<TdOrder> orderInfo = tdOrderService.selectOrderInfoByUserId(userID);
        if (null!=orderInfo) {
            return AjaxResult.success().put("orderInfo", orderInfo);
        }
        return AjaxResult.error("查询用户订单失败");
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('xiaomi_mall:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TdOrder tdOrder) {
        return toAjax(tdOrderService.updateTdOrder(tdOrder));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('xiaomi_mall:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tdOrderService.deleteTdOrderByIds(ids));
    }
}
